/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Server.BUS;

import Server.DTO.Database;
import Server.BUS.Transporter;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author QuangKhai
 */
public class DBServerListener implements Runnable{
    private Socket socket;
    private ServerSocket serverSocket;
    private String username;
    private String password;       
    private Thread skThread = new Thread();
    private List<Database> lstDB = new ArrayList<Database>();
    
    public DBServerListener(int port, List<Database> _lstDB) throws IOException{
        this.serverSocket = new ServerSocket(port);
        //this.serverSocket.bind(new InetSocketAddress(address, port));                     
        this.lstDB = _lstDB;
    }
    
    public void setConnection() throws IOException{
        while(true){
            this.socket = serverSocket.accept();            
            
            if(skThread.isAlive()){                
                int confirm = JOptionPane.showConfirmDialog(null, "Another client want to connect");
                if(confirm == JOptionPane.YES_OPTION) {
                    skThread.suspend();
                    skThread = new Thread(new Transporter(socket, lstDB));
                    skThread.start();          
                }                
            }else{                      
                skThread = new Thread(new Transporter(socket, lstDB));
                skThread.start();                          
            }          
        }
    }
    
    @Override
    public void run() {
        try {
            setConnection();
        } catch (IOException ex) {
            Logger.getLogger(DBServerListener.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
}
